<template>
  <div>
    <el-card shadow="never">
      <div class="describe">
        <div>
          <el-text class="mx-1" size="large">指定模式:</el-text>
          <el-text class="mx-1">
            若设备指定了接码ID，则使用该接码ID, 如果接码实例未启用或应用类型不符，直接返回错误。
          </el-text>
        </div>
        <div>
          <el-text class="mx-1" size="large">固定模式:</el-text>
          <el-text class="mx-1">使用预设的接码ID。</el-text>
        </div>
        <div>
          <el-text class="mx-1" size="large">随机模式:</el-text>
          <el-text class="mx-1">从同应用已启用实例中随机选择接码ID。</el-text>
        </div>
        <div>
          <el-text class="mx-1" size="large">条件模式:</el-text>
          <el-text class="mx-1">若设备名匹配规则，使用对应接码ID</el-text>
        </div>
        <div>
          <el-text class="mx-1" size="large">注意:</el-text>
          <el-text class="mx-1">固定、随机、条件模式均在设备未指定接码ID时生效。</el-text>
        </div>
      </div>

      <el-form
        ref="ruleFormRef"
        v-loading="getRoleListLoading"
        :rules="rules"
        :model="setting"
        label-width="auto"
        style="width: 900px"
      >
        <el-form-item label="配置模块" prop="mode">
          <el-select v-model="setting.mode" placeholder="请选择模式">
            <el-option label="固定模式" value="fixed" />
            <el-option label="随机模式" value="random" />
            <el-option label="条件模式" value="rule" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="setting.mode === 'fixed'" label="选择平台" prop="cfgId">
          <el-select
            v-model="setting.cfgId"
            style="width: 100%"
            filterable
            remote
            :remote-method="remoteMethod"
            placeholder="请选择平台"
            clearable
          >
            <div v-loading="loading">
              <el-option
                v-for="item in selectList"
                :key="item.row.id"
                :value="item.row.id"
                :label="item.row.id"
              >
                <div>
                  <span>{{ item.row.id || "--" }} /</span>
                  <span>{{ item.row.remark || "--" }} /</span>
                  <span>{{ item.row.name || "--" }} /</span>
                  <span>
                    <span
                      v-if="item.row.countryCode"
                      style="margin-left: 2px"
                      :class="`flag-icon flag-icon-${
                        item.row.countryCode.length > 2
                          ? getCountriesListIcon(item.row.countryCode)?.toLowerCase()
                          : item.row.countryCode.toLowerCase()
                      }`"
                    ></span>
                    <span v-if="item.row.countryCode" style="margin-left: 2px">
                      {{
                        item.row.countryCode.length > 2
                          ? getCountriesListIcon(item.row.countryCode)
                          : item.row.countryCode
                      }}
                    </span>
                  </span>
                </div>
              </el-option>
            </div>
            <template #footer>
              <el-pagination
                v-model:current-page="paging.page"
                v-model:page-size="paging.size"
                :page-sizes="['10', '20', '30', '50', '100']"
                :background="true"
                layout="total, prev, pager, next"
                :total="paging.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item v-if="setting.mode === 'rule'" prop="rules" label="规则列表">
          <el-table :data="setting.rules" style="width: 100%" border>
            <el-table-column prop="condition" label="设备名称匹配规则" align="center">
              <template #default="scope">
                <el-form-item :prop="`rules.${scope.$index}.condition`" :rules="rules.condition">
                  <el-select v-model="scope.row.condition" placeholder="请选择设备名称匹配规则">
                    <el-option label="等于" value="equal" />
                    <el-option label="包含" value="contain" />
                    <el-option label="以...开头" value="startWith" />
                    <el-option label="以...结尾" value="endWith" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="match" label="匹配内容" align="center">
              <template #default="scope">
                <el-form-item :prop="`rules.${scope.$index}.match`" :rules="rules.match">
                  <el-input
                    v-if="setting.mode === 'rule'"
                    v-model="scope.row.match"
                    type="text"
                    placeholder="请输入匹配内容"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="cfgId" label="选择平台" align="center">
              <template #default="scope">
                <el-form-item
                  v-if="setting.mode === 'rule'"
                  :prop="`rules.${scope.$index}.cfgId`"
                  :rules="rules.cfgId"
                >
                  <el-select
                    v-model="scope.row.cfgId"
                    filterable
                    remote
                    :remote-method="remoteMethod"
                    placeholder="请选择平台"
                    clearable
                    style="width: 240px"
                  >
                    <div v-loading="loading">
                      <el-option
                        v-for="item in selectList"
                        :key="item.row.id"
                        :value="item.row.id"
                        :label="item.row.id"
                      >
                        <div>
                          <span>{{ item.row.id || "--" }} /</span>
                          <span>{{ item.row.remark || "--" }} /</span>
                          <span>{{ item.row.name || "--" }} /</span>
                          <span>
                            <span
                              v-if="item.row.countryCode"
                              style="margin-left: 2px"
                              :class="`flag-icon flag-icon-${
                                item.row.countryCode.length > 2
                                  ? getCountriesListIcon(item.row.countryCode)?.toLowerCase()
                                  : item.row.countryCode.toLowerCase()
                              }`"
                            ></span>
                            <span v-if="item.row.countryCode" style="margin-left: 2px">
                              {{
                                item.row.countryCode.length > 2
                                  ? getCountriesListIcon(item.row.countryCode)
                                  : item.row.countryCode
                              }}
                            </span>
                          </span>
                        </div>
                      </el-option>
                    </div>
                    <template #footer>
                      <el-pagination
                        v-model:current-page="paging.page"
                        v-model:page-size="paging.size"
                        :page-sizes="['10', '20', '30', '50', '100']"
                        :background="true"
                        layout="total, prev, pager, next"
                        :total="paging.total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                      />
                    </template>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="match" label="操作" align="center">
              <template #default="scope">
                <el-button type="danger" text @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button size="small" :icon="Plus" style="width: 100%" @click="handleAddProduct">
            添加
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="clickDeleteRuleList">删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { Plus } from "@element-plus/icons-vue";
import useToggle from "@/hooks/useToggle";
import {
  getRuleList,
  configList,
  setRuleList,
  deleteRuleList,
} from "@/api/platformConfig/index.api";
import useCountries from "@/hooks/useCountries";
const { getCountriesListIcon } = useCountries();
const [loading, _, setLoading] = useToggle();
const OldSeting = ref({});
const ruleFormRef = ref();

const setting = ref({});

const paging = ref({
  page: 1,
  size: 10,
  total: 0,
});

const rules = reactive({
  mode: [
    {
      required: true,
      message: "请输入配置模块",
      trigger: "change",
    },
  ],
  condition: [{ required: true, message: "请选择设备名称匹配规则", trigger: "change" }],
  match: [{ required: true, message: "请输入匹配内容", trigger: "blur" }],
  cfgId: [
    {
      required: true,
      message: "请选择平台",
      trigger: "change",
    },
  ],
  rules: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (setting.value.mode === "rule" && (!value || value.length === 0)) {
          callback(new Error("请至少添加一条规则"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});

watch(
  () => setting.value.mode,
  (newVal) => {
    if (newVal === "rule") {
      // 如果模式是条件模式，则初始化规则数组

      if (OldSeting.value.mode === newVal) {
        setting.value = JSON.parse(JSON.stringify(OldSeting.value));
      } else {
        setting.value.rules = [
          {
            condition: "",
            match: "",
          },
        ];
      }
    } else if (newVal === "fixed") {
      if (OldSeting.value.mode === newVal) {
        setting.value = {
          mode: newVal,
          cfgId: JSON.parse(JSON.stringify(OldSeting.value.cfgId)),
        };
      } else {
        setting.value = {
          mode: newVal,
          cfgId: "",
        };
      }
    } else {
      // 如果不是条件模式，则清空规则数组
      setting.value = {
        mode: newVal,
      };
    }
  }
);

const submitForm = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      getRoleListLoading.value = true;
      const res = await setRuleList(setting.value).finally(() => ElMessage.success("保存成功"));
      GetRoleList();
      console.log(res);
      getRoleListLoading.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};

const clickDeleteRuleList = () => {
  ElMessageBox.confirm("确认要删除这条规则吗", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    getRoleListLoading.value = true;
    const res = await deleteRuleList().finally(() => {
      ElMessage.success("删除成功");
      getRoleListLoading.value = false;
      GetRoleList();
    });
    console.log(res);
  });
};

const handleAddProduct = () => {
  if (setting.value.rules.length < 10) {
    setting.value.rules.push({
      condition: "",
      match: "",
    });
  } else {
    ElMessage.warning("最多添加10条规则");
  }
};

const handleDelete = (index) => {
  if (setting.value.rules.length > 1) {
    ElMessageBox.confirm("确认要删除这条规则吗", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      setting.value.rules.splice(index, 1);
    });
  } else {
    ElMessage.warning("至少保留一条配置");
  }
};

const handleSizeChange = (e) => {
  paging.value.size = e;
  remoteMethod("");
};
const handleCurrentChange = (e) => {
  paging.value.page = e;
  remoteMethod("");
};

const selectList = ref([]);

const remoteMethod = async (query) => {
  setLoading(true);
  const res = await configList({
    page: paging.value.page,
    size: paging.value.size,
    name: query,
  }).finally(() => {
    setLoading(false);
  });
  paging.value.total = res.count;
  selectList.value = res.rows;
};

const getRoleListLoading = ref(false);

const GetRoleList = async () => {
  getRoleListLoading.value = true;
  setLoading(true);
  const res = await getRuleList().finally(() => (getRoleListLoading.value = false));
  if (!res) {
    OldSeting.value = {};
    setting.value = {};
    return;
  }
  OldSeting.value = JSON.parse(JSON.stringify(res.setting));
  setting.value = res.setting;
};

onMounted(() => {
  remoteMethod(""); // 传空字符串，获取全部或默认数据
  GetRoleList();
});
</script>

<style scoped lang="scss">
.describe {
  margin-bottom: 30px;
  font-size: 18px;
  div {
    padding: 5px;
    .mx-1:nth-child(1) {
      display: inline-block;
      width: 80px;
      font-weight: 500;
      white-space: nowrap; /* 禁止换行 */
    }
    .mx-1:nth-child(2) {
      display: inline-block;
      white-space: nowrap; /* 禁止换行 */
    }
  }
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

:deep(.el-table--default .cell) {
  padding-bottom: 16px;
}
</style>
